package org.example.project.common.contant;

import lombok.Data;
import org.example.project.common.error.MessageEnum;
import org.example.project.common.error.enums.ErrorCode;
import org.example.project.common.error.exception.ServiceException;

import java.io.Serializable;

/**
 * 统一API响应结果封装
 *
 * @author jacky.liu
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private String resCode;
    private String resMsg;
    private T data;
    private boolean success;

    private R() {
    }

    private R(MessageEnum resultCode, T data, boolean success) {
        this(resultCode.code(), resultCode.msg(), data, success);
    }

    private R(String resCode, String resMsg, T data, boolean success) {
        this.resCode = resCode;
        this.resMsg = resMsg;
        this.data = data;
        this.success = success;
    }

    public Boolean notSuccess() {
        return !isSuccess();
    }

    public static R<String> success() {
        return success(null);
    }

    public static <T> R<T> success(T data) {
        return new R<>(ErrorCode.SUCCESS, data, true);
    }

    public static R<String> fail(MessageEnum resultCode) {
        return new R<>(resultCode, null, false);
    }

    public static R<String> fail(MessageEnum resultCode, String message) {
        return new R<>(resultCode, message, false);
    }

    public static R<String> fail(RuntimeException exception) {
        if (exception instanceof ServiceException) {
            ServiceException e = (ServiceException) exception;
            return new R<>(e.getMessageEnum(), e.getMessage(), false);
        }
        return new R<>(ErrorCode.B0001, exception.getMessage(), false);
    }

    public static <T> R<T> of(MessageEnum messageEnum, T detail, boolean success) {
        return new R<>(messageEnum, detail, success);
    }

}
